package com.shazhu.api.nongjt;


import com.alibaba.fastjson2.JSONObject;

import com.shazhu.common.constant.CacheConstants;
import com.shazhu.common.constant.Constants;
import com.shazhu.common.core.domain.AjaxResult;
import com.shazhu.common.core.domain.model.LoginUser;
import com.shazhu.common.core.redis.RedisCache;
import com.shazhu.common.enums.SmsEnum;
import com.shazhu.common.utils.nongjt.SmsUtils;
import com.shazhu.framework.web.service.SysLoginService;
import com.shazhu.framework.web.service.TokenService;

import com.shazhu.nongjt.domain.NjtUserPerfect;
import com.shazhu.nongjt.domain.NjtUserRegister;
import com.shazhu.nongjt.domain.vo.NjtLoginUser;
import com.shazhu.nongjt.domain.vo.NjtUserLoginVO;
import com.shazhu.nongjt.domain.vo.NjtUserRegisterVO;
import com.shazhu.nongjt.service.INjtCommonService;
import com.shazhu.nongjt.service.INjtUserPerfectService;
import com.shazhu.nongjt.service.INjtUserRegisterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import java.util.regex.Pattern;

@Tag(name = "会员管理")
@RestController
@RequestMapping("/api/user")
public class NjtUserAPI {
    @Autowired
    private INjtUserRegisterService userRegisterService;
    @Autowired
    private static final Logger log = LoggerFactory.getLogger(NjtUserAPI.class);
    /**
     * 校验⼿机号是否可以被注册
     *
     * @param mobilePhone 注册⼿机号
     * @return
     */
    @Operation(summary = "校验⼿机号是否可以被注册")
    @GetMapping("/checkMobilePhone")
    public AjaxResult checkMobilePhone(
            @Parameter(name = "mobilePhone", description = "注册⼿机号", required = true, schema = @Schema(type = "string"))
            @RequestParam("mobilePhone") String mobilePhone) {
        NjtUserRegister userRegister = userRegisterService.getByMobilePhone(mobilePhone);
        if (null != userRegister) {
            return AjaxResult.error("该⼿机号已被注册,请更换注册⼿机号");
        }
        return AjaxResult.success("⼿机号可⽤");
    }
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SmsUtils smsUtils;
    /**
     * 发送短信验证码
     *
     * @param mobilePhone ⼿机号
     * @return
     */
    @Operation(summary = "发送短信验证码")
    @GetMapping("/sendValidateCode")
    public AjaxResult sendValidateCode(
            @Parameter(name = "mobilePhone", description = "⼿机号", required =
                    true, schema = @Schema(type = "string"))
            @RequestParam("mobilePhone") String mobilePhone) {
        // 正则表达式校验⼿机号格式
        if (!Pattern.compile("^1[3-9]\\d{9}$").matcher(mobilePhone).matches())
        {
            return AjaxResult.error("⼿机号格式不正确");
        }
        // 检查是否在冷却期（60秒内只能发送⼀次）
        String cooldownKey = CacheConstants.SMS_COOLDOWN_PREFIX + mobilePhone;
        if (redisCache.hasKey(cooldownKey)) {
            return AjaxResult.error("请求过于频繁，请稍后再试");
        }
        // ⽣成6位随机验证码
// String code = ValidateCodeUtils.generateValidateCode(6);
        // ⽅式⼆：⽣成6位随机验证码
        String code = String.valueOf(ThreadLocalRandom.current().nextInt(100000, 999999));
//        // 调⽤阿⾥云短信接⼝，给⽤户发送短信
//        JSONObject param = new JSONObject();
//        param.put("code", code);
//        Boolean result = smsUtils.sendSms(mobilePhone, param, SmsEnum.REGISTER_TEMPLATE_CODE);
//        if (!result) {
//            log.info("短信发送接⼝，⼿机号，{}，验证码：{}，发送失败！", mobilePhone,
//                    code);
//            return AjaxResult.error("发送失败");
//        }
//        log.info("短信发送接⼝，⼿机号，{}，验证码：{}，发送成功！", mobilePhone, code);
        // 将验证码放⼊Redis 设置失效时间为5分钟
        redisCache.setCacheObject(CacheConstants.SMS_CODE_PREFIX + mobilePhone
                , code, 5, TimeUnit.MINUTES);
        // 设置冷却期
        redisCache.setCacheObject(cooldownKey, "locked", 60, TimeUnit.SECONDS);

        return AjaxResult.success("发送成功", code);

}
    /**
     * 会员注册
     *
     * @param registerVO
     * @return
     */
    @Operation(summary = "会员注册")
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody NjtUserRegisterVO registerVO) {
        String mobilePhone = registerVO.getMobilePhone();
        String password = registerVO.getPassword();
        String checkCode = registerVO.getCheckCode();
        // ⽐对验证码是否⼀致
        String code = redisCache.getCacheObject(CacheConstants.SMS_CODE_PREFIX + mobilePhone);
        if (!checkCode.equals(code)) {
            return AjaxResult.error("验证码有误");
        }
        // 保存注册信息
        return userRegisterService.saveRegister(mobilePhone, password);
    }
    @Autowired
    private SysLoginService loginService;
    /**
     * 会员登录
     *
     * @param loginVO 登录信息
     * @return 结果
     */
    @Operation(summary = "会员登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody NjtUserLoginVO loginVO) {
        // ⽣成token
        String token = loginService.appLogin(loginVO.getUsername(), loginVO.getPassword());
        AjaxResult result = AjaxResult.success();
        result.put(Constants.TOKEN, token);
        return result;
    }
    @Autowired
    private TokenService tokenService;
    /**
     * 登出
     *
     * @param request request对象
     * @return 是否登出成功
     */
    @Operation(summary = "登出接⼝")
    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {

        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser == null) {
            return AjaxResult.error("⽆法获取⽤户信息");
        }
        tokenService.delLoginUser(loginUser.getToken());
        return AjaxResult.success();
    }
    /**
     * 忘记或修改密码
     *
     * @param registerVO
     * @return
     */
    @Operation(summary = "忘记或修改密码")
    @PostMapping("/forgotPassword")
    public AjaxResult forgotPassword(@Valid @RequestBody NjtUserRegisterVO registerVO) {
        String mobilePhone = registerVO.getMobilePhone();
        String password = registerVO.getPassword();
        String checkCode = registerVO.getCheckCode();
        // ⽐对验证码是否⼀致
        String code = redisCache.getCacheObject(CacheConstants.SMS_CODE_PREFIX
                + mobilePhone);
        if (!checkCode.equals(code)) {
            return AjaxResult.error("验证码有误");
        }
        // 更改注册信息
        return userRegisterService.updateRegister(mobilePhone, password);
    }
    @Autowired
    private INjtCommonService commonService;
    /**
     * 获取当前登录⽤户信息
     *
     * @return
     */

    @Operation(summary = "获取当前登录⽤户信息")
    @GetMapping("/queryLoginUser")
    public AjaxResult queryLoginUser() {
        NjtLoginUser loginUser = commonService.getLoginUser();
        return AjaxResult.success(loginUser);
    }
    /**
     * 刷新token
     *
     * @param request
     * @return
     */

    @Operation(summary = "刷新token")
    @PostMapping("/refreshToken")
    public AjaxResult refreshToken(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        tokenService.refreshToken(loginUser);
        return AjaxResult.success("刷新成功");
    }
    @Autowired
    private INjtUserPerfectService userPerfectService;
    /**
     * 完善信息
     *
     * @param
     * @return
     */
    @Operation(summary = "完善信息")
    @PostMapping("/perfect")
    public AjaxResult perfect(@RequestBody NjtUserPerfect userPerfect) {
        return userPerfectService.perfectUser(userPerfect);
    }
}
